from socket import *
from multiprocessing import *
import re
import os

#自己写的


def fun(new_socket):
    pass
    #接收数据
    #解析报文
    #提取请求方式
    #提取路径
        # HTML_ROOT_DIR="./html"
        # path = /index.html
        # file = open("index.html")
        # data = file.read()
        # file.close()
    #返回响应数据
    #HTTP1.1 200 OK\r\n
    #\r\n
    #hello word
    #send()
    #close()



#处理浏览器请求并返回数据,返回浏览器数据
def back_data(data):
    PATH_ROOT_DIR = "./html"
    responseHeaderLines = "HTTP/1.1 200 OK\r\n"
    responseHeaderLines += "\r\n"
    request_list = re.split(r"\r\n", data)
    request_list_0 = re.split(r" ", request_list[0])
    request = request_list_0[0]
    path = request_list_0[1]
    file_path = PATH_ROOT_DIR + path
    if os.path.exists(path):
        if file_path == PATH_ROOT_DIR + "/":
            path = file_path + "index.html"
            file = open(path)
            responseBody = file.read()
            file.close()

    else:
        responseHeaderLines = "HTTP/1.1 404 Not Fount\r\n"
        responseHeaderLines += "\r\n"
        responseBody = "404"

    data = responseHeaderLines + responseBody
    return data

# 处理客户端的请求并为其服务
def dealWithClient(newSocket,destAddr):
    recvData = newSocket.recv(1024).decode()
    if len(recvData)>0:
        print('recv[%s]:%s'%(str(destAddr), recvData))
        response = back_data(recvData)
        newSocket.send(response.encode())
    else:
        print('[%s]客户端已经关闭'%str(destAddr))
    newSocket.close()


def main(port):

    serSocket = socket(AF_INET, SOCK_STREAM)
    serSocket.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
    localAddr = ('', port)
    serSocket.bind(localAddr)
    serSocket.listen(5)

    try:
        while True:
            print("-----主进程，等待新客户端的到来------")
            newSocket,destAddr = serSocket.accept()

            print("-----主进程，接下来创建一个新的进程负责数据处理[%s]-----"%str(destAddr))
            client = Process(target=dealWithClient, args=(newSocket,destAddr))
            client.start()

            #因为已经向子进程中copy了一份（引用），并且父进程中这个套接字也没有用处了
            #所以关闭
            newSocket.close()
    finally:
        #当为所有的客户端服务完之后再进行关闭，表示不再接收新的客户端的链接
        serSocket.close()

if __name__ == '__main__':
    main(8080)